const express = require("express");
const { Article } = require("../../models");
const router = express.Router();
const Sequelize = require("sequelize");
const { NotFoundError } = require("../../utils/errors");
const { success, failure } = require("../../utils/responses");
const Op = Sequelize.Op;

/**
 * 获取文章列表
 * GET /admin/articles
 */
router.get("/", async function (req, res) {
  try {
    const query = req.query;
    const currentPage = Math.abs(Number(query.currentPage)) || 1;
    const pageSize = Math.abs(Number(query.pageSize)) || 10;
    const offset = (currentPage - 1) * pageSize;
    const condition = {
      order: [["id", "DESC"]],
      offset,
      limit: pageSize,
    };
    if (query.title) {
      condition.where = {
        title: {
          [Op.like]: `%${query.title}%`,
        },
      };
    }
    const articles = await Article.findAndCountAll(condition);
    success(res, "Get articles successfully", {
      articles: articles.rows,
      total: articles.count,
      currentPage,
      pageSize,
    });
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 根据id获取文章
 * GET /admin/articles/:id
 */
router.get("/:id", async function (req, res) {
  try {
    const article = await getArticle(req);
    success(res, "Get article successfully", { article });
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 创建文章
 * POST /admin/articles
 */
router.post("/", async function (req, res) {
  try {
    const body = filterBody(req.body);
    const article = await Article.create(body);
    success(res, "Create article successfully", { article }, 201);
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 删除文章
 * DELETE /admin/articles/:id
 */
router.delete("/:id", async function (req, res) {
  try {
    const article = await getArticle(req);
    await article.destroy();
    success(res, "Delete article successfully");
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 更新文章
 * PUT /admin/articles/:id
 */
router.put("/:id", async function (req, res) {
  try {
    const article = await getArticle(req);
    await article.update(filterBody(req.body));
    success(res, "Update article successfully", { article });
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 公共方法： 过滤请求体
 */
function filterBody(body) {
  const { title, content } = body;
  return {
    title,
    content,
  };
}

/**
 * 公共方法： 查询当前文章
 */
async function getArticle(req) {
  const { id } = req.params;
  const article = await Article.findByPk(id);
  if (!article) {
    throw new NotFoundError(`ID: ${id}的文章未找到`);
  }
  return article;
}

module.exports = router;
